<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        @keyup.enter.native="loadData"
        clearable
        size="small"
        style="width: 200px;"
        class="filter-item"
        placeholder="商品名称"
        v-model="params.goodsTitle"
      ></el-input>
      <el-input
        @keyup.enter.native="loadData"
        clearable
        size="small"
        style="width: 200px;"
        class="filter-item"
        placeholder="商品编码"
        v-model="params.goodsNo"
      ></el-input>
      <el-select v-model="params.goodsStatus" clearable placeholder="商品状态" size="small">
        <el-option
          v-for="(item,index) in goodsStatusData()"
          :key="index"
          :label="item"
          :value="index"
        ></el-option>
      </el-select>
      <category-cascader :clearable="true" v-model="params.categoryPath"></category-cascader>
      <el-button
        class="filter-item"
        type="primary"
        size="small"
        v-waves
        icon="el-icon-search"
        @click="loadData"
      >搜索</el-button>
      <el-button
        class="filter-item"
        type="primary"
        v-waves
        icon="el-icon-plus"
        size="small"
        @click="handleImportGoods"
      >导入商品</el-button>
      <el-button
        class="filter-item"
        type="primary"
        v-waves
        icon="el-icon-document"
        size="small"
        @click="exportExcelFile"
      >导出</el-button>
    </div>
    <el-table
      :data="list"
      :height="tableHeight"
      @sort-change="sortChange"
      v-loading="listLoading"
      element-loading-text="给我一点时间"
      border=""
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column align="center" type="index" label="序号" width="60" fixed="left"></el-table-column>
      <el-table-column prop="cover" align="center" label="封面" width="140" fixed="left">
        <template slot-scope="scope">
          <img :src="scope.row.cover|absUrl" alt="" class="avatar">
        </template>
      </el-table-column>
      <el-table-column prop="goodsNo" align="center" label="商品编号" width="90" fixed="left">
        <template slot-scope="scope">
          <span>{{scope.row.goodsNo}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="title" align="center" label="商品名称" width="160" fixed="left">
        <template slot-scope="scope">
          <span>{{scope.row.title}}</span>
          <div class="sale-props">{{saleProps(scope.row.saleProps)}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="categoryId" align="center" label="供应商名称" width="100">
        <template slot-scope="scope">
          <!-- <span>{{scope.row.goodsCategoryName}}</span> -->
          <span>{{scope.row.providerName}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="marketPrice" align="center" label="市场价" width="80">
        <template slot-scope="scope">
          <span>{{scope.row.marketPrice}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="price" align="center" label="微信价" width="80">
        <template slot-scope="scope">
          <span>{{scope.row.price}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="points" align="center" label="积分价" width="80">
        <template slot-scope="scope">
          <span>{{scope.row.points}}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="tagIds" align="center" label="商品标签" width="100">
        <template slot-scope="scope">
          <span>{{scope.row.tagName}}</span>
        </template>
      </el-table-column>-->
      <el-table-column prop="brandName" align="center" label="品牌" width="160">
        <template slot-scope="scope">
          <span>{{scope.row.brandName}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="sort" align="center" label="排序" width="130">
        <template slot-scope="scope">
          <el-input-number
            v-model="scope.row.sort"
            style="width:100px"
            @change="changeSort(scope.row)"
            size="mini"
          ></el-input-number>
        </template>
      </el-table-column>
      <el-table-column prop="status" align="center" label="商品状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status|tagStatus">{{scope.row.status|goodsStatus}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="stock" align="center" label="商品库存" width="100">
        <template slot-scope="scope">
          <span>{{scope.row.stock}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="160">
        <template slot-scope="scope">
          <div class="btns">
            <el-button size="mini" type="danger" @click="handleLeave(scope.row)">移出</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background=""
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="params.pageNo"
        :page-sizes="[10,20,30,50]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <el-dialog title="导入商品" :visible.sync="dialogFormVisible" width="1300px">
      <goods-select
        :themeId="$route.query.id"
        :auto-load="false"
        ref="goodsSelectDom"
        :queryType='3'
        @on-import-all="onImportAll"
        @on-import-selected-items="onImportSelectedItems"
      ></goods-select>
    </el-dialog>
  </div>
</template>

<script>
import categoryCascaderVue from '../../components/categoryCascader.vue'
import goodsSelect from '../../components/goodsSelect.vue'
import { Loading } from 'element-ui'
export default {
  components: {
    'category-cascader': categoryCascaderVue,
    'goods-select': goodsSelect
  },
  data () {
    return {
      tableHeight: 400,
      hasNewGoodRules: false,
      uillUpdateImg: false,
      isAddingRule: false,
      total: 0,

      goodsTagItems: [],
      params: {
        pageSize: 10,
        pageNo: 1
      },

      temp: {
        id: '',
        imgSrcs: '',
        cover: '',

        categoryId: '',

        typeId: '',

        title: '',

        intro: '',
        categoryPath: '',
        shopNo: '',

        goodsUnit: '',

        tagIds: '',

        status: '',

        freightTemplateId: '',

        marketPrice: '',

        price: 0,

        points: '',
        goodsRule: '',
        goodsNo: '',

        stock: '',

        alertStock: '',

        content: '',

        brandId: ''
      },
      ruleDialogVisible: false,
      rules: {
        cover: [
          {
            required: true,
            message: '封面不能为空',
            trigger: 'change'
          }
        ],
        categoryPath: [
          {
            required: true,
            message: '所属分类不能为空',
            trigger: 'change'
          }
        ],

        imgSrcs: [
          {
            required: true,
            message: '请上传至少一张商品图片',
            trigger: 'change'
          }
        ],

        title: [
          {
            required: true,
            message: '商品名称不能为空',
            trigger: 'change'
          },
          {
            max: 60,
            message: '商品名称不能大于60个字',
            trigger: 'change'
          }
        ],

        intro: [
          {
            required: true,
            message: '商品简介不能为空',
            trigger: 'change',
            max: 900
          }
        ],

        shopNo: [
          {
            required: true,
            message: '商家编码不能为空',
            trigger: 'change',
            max: 60
          }
        ],

        goodsUnit: [
          {
            required: true,
            message: '计量单位不能为空',
            trigger: 'change',
            max: 60
          }
        ],

        status: [
          {
            required: true,
            message: '销售状态未指定',
            trigger: 'change'
          }
        ],

        freightTemplateId: [
          {
            required: true,
            message: '运费模板不能为空',
            trigger: 'change'
          }
        ],

        marketPrice: [
          {
            required: true,
            message: '市场价不能为空',
            trigger: 'change'
          }
        ],

        price: [
          {
            required: true,
            message: '微信价不能为空',
            trigger: 'change'
          }
        ],

        points: [
          {
            required: true,
            message: '积分价不能为空',
            trigger: 'change'
          }
        ],

        goodsNo: [
          {
            required: true,
            message: '货号不能为空',
            trigger: 'change',
            max: 60
          }
        ],

        stock: [
          {
            required: true,
            message: '商品库存不能为空',
            trigger: 'change'
          }
        ],

        alertStock: [
          {
            required: true,
            message: '警戒库存不能为空',
            trigger: 'change'
          }
        ],

        content: [
          {
            required: true,
            message: '商品详情不能为空',
            trigger: 'change'
          }
        ],

        brandId: [
          {
            required: true,
            message: '请选择品牌',
            trigger: 'change'
          }
        ]
      }
    }
  },

  created () {
    // let id = this.$route.query.id;
    // if (id) {
    //   // this.init("goods_special", 2)
    //   //   .addParam("extra", id)
    //   //   .loadData();
    //   this.$post('/admin/share_activity/goods/list',{id}).then(data=>{
    //     this.list = data.data;
    //     this.total = data.total;
    //   });
    // }
    // this.combOptions("goods_tag").then(info => {
    //   this.goodsTagItems = info;
    // });
    this.tableHeight = window.innerHeight - 320
    this.loadData()
  },
  methods: {
    loadData () {
      let id = this.$route.query.id
      this.$post('/admin/share_activity/goods/list', { id, ...this.params }).then(
        data => {
          this.list = data.data
          this.total = data.totalRecord
        }
      )
    },
    changeSort (row) {
      this.$post('/admin/share_activity/goods/set_sort', {
        relationId: row.relationId,
        sort: row.sort
      })
    },
    handleCurrentChange () {
      this.loadData()
    },
    handleSizeChange (val) {
      this.params.pageSize = parseInt(`${val}`)
      this.loadData()
    },
    saleProps (prop) {
      if (prop && prop != '{}') {
        prop = JSON.parse(prop)
        const rt = []
        for (const key in prop) {
          rt.push(key + ':' + prop[key])
        }
        return '(' + rt.join(',') + ')'
      }
      return ''
    },
    handleLeave (row) {
      // /goods/delete_relation
      this.$$comfirm('确定移除该商品吗？', _ => {
        let id = this.$route.query.id
        this.$post('/admin/share_activity/goods/delete_relation', {
          skuId: [row.id],
          id
        }).then(_ => {
          this.loadData()
          this.$refs['goodsSelectDom'].handleFilter()
          this.$$notify()
        })
      })
    },
    onImportSelectedItems (ids) {
      this.$confirm('确定导入所选商品吗?', '提示').then(rt => {
        let loadingInstance1 = Loading.service({ fullscreen: true })
        let id = this.$route.query.id
        this.$post(
          '/admin/share_activity/goods/add_relation',
          Object.assign(
            {
              id: id
            },
            {
              skuId: ids.split(',')
            }
          )
        )
          .then(data => {
            this.$$notify('导入成功')
            this.loadData()
            loadingInstance1.close()
            this.$refs['goodsSelectDom'].handleFilter()
            this.dialogFormVisible = false
          })
          .catch(_ => {
            loadingInstance1.close()
          })
      })
    },
    onImportAll (filterRules) {
      if (filterRules == '[]') {
        this.$warning('请填写查询条件')
        return
      }
      this.$confirm('确定全部导入吗?', '提示').then(rt => {
        // let id = this.$route.query.id;
        // if (id) {
        //   let loadingInstance1 = Loading.service({ fullscreen: true });
        //   this.$post("/admin/goods/import2special", {
        //     filterRules,
        //     specialId: id
        //   })
        //     .then(data => {
        //       this.$$notify("导入成功");
        //       this.loadData();
        //       loadingInstance1.close();
        //       this.dialogFormVisible = false;
        //     })
        //     .catch(_ => {
        //       loadingInstance1.close();
        //     });
        // }
      })
    },
    handleImportGoods () {
      this.dialogFormVisible = true
      setTimeout(() => {
        this.$refs.goodsSelectDom.handleFilter()
      }, 20)
    },
    submitRuleFormAction () {
      if (this.submiting) {
        return
      }
      let data = this.$refs['goodsRule'].getData()
      this.submiting = true
      this.$post('/admin/goods/saveGoodsRule', {
        id: this.temp.id,
        goodsRule: JSON.stringify(data)
      })
        .then(_ => {
          this.ruleDialogVisible = false
          this.$$notify('操作成功')
          this.submiting = false
        })
        .catch(_ => {
          this.submiting = false
        })
    },
    showRuleDialog (row) {
      this.temp.goodsRule = row.goodsRule
      this.temp.id = row.id
      this.ruleDialogVisible = true
    },
    __onParseFilterValue (field, eq, value) {
      if (value) {
        if (field == 'goods_category.path') {
          return ',' + value.replace(/^,|,$/g, '') + ','
        }
      }
      return value
    },
    handleCommand (row, command) {
      let postData = value => {
        this.$post('/admin/goods/' + command, {
          id: row.id,
          approve_remark: value
        }).then(res => {
          if (row.audit_step == 9) {
            row.audit_step = 2
          } else {
            row.audit_step = 9
          }
          this.$$notify('操作成功')
        })
      }
      if (command == 'unAuthPassed') {
        this.$prompt('请输入审核拒绝理由', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
          .then(({ value }) => {
            postData(value)
          })
          .catch(() => {})
      } else {
        this.$$comfirm('确定审核通过吗？', () => {
          postData()
        })
      }
    },
    exportExcelFile () {
      this.$post('/admin/share_activity/goods/export', {
        id: this.$route.query.id,
        title: '商品',
        fields: JSON.stringify([
          {
            field: 'goodsNo',
            title: '商品编号'
          },
          {
            field: 'title',
            title: '商品名称'
          },
          {
            field: 'providerName',
            title: '供应商名称'
          },
          {
            field: 'marketPrice',
            title: '市场价'
          },
          {
            field: 'price',
            title: '微信价'
          },
          {
            title: '积分价',
            field: 'points'
          },
          {
            title: '品牌',
            field: 'brandName'
          },
          {
            field: 'status',
            title: '商品状态',
            valueMap: this.goodsStatusData()
          },
          {
            title: '商品库存',
            field: 'stock'
          }
        ])
      }).then(info => {
        this.openWin(info)
      })
    }
  }
}
</script>
<style scoped>
.avatar {
  width: 100px;
  display: block;
  margin: 0 auto;
  height: 100px;
}
.btns {
  padding-left: 15px;
  text-align: left;
}
.btns /deep/ button {
  margin-top: 10px;
  margin-bottom: 10px;
}
</style>
